package com.hit.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hit.oss.service.OssService;
import com.hit.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@CrossOrigin//跨域
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId=ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret=ConstantPropertiesUtils.KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;

        try {
            //创建oss实例
            OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream=file.getInputStream();
            //调用oss方法实现上传
            String fileName=file.getOriginalFilename();
            //文件名会出现重复，所以加入uuid保证没有重复
            String uuid= UUID.randomUUID().toString().replaceAll("-","");
            fileName=uuid+fileName;
            //把上传的文件按照时间分到不同的文件夹中，如2022/11/3/ansacuacnuscununcsuns05.jpg
            //获取时间使用joda-time
            String datePath=new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+"/"+fileName;
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭ossClient
            ossClient.shutdown();

            //返回上传后的文件的url
            String url= "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
